package com.zh.common.utils

import android.text.InputFilter
import android.text.Spanned
import java.util.regex.Pattern

internal class InputMoneyFilter(canNegative: Boolean, maxLen: Int) : InputFilter {

    var pattern: String
    //包含maxLen, 得-1
    init {
        pattern = "(([0]|(0[.]\\d{0,2}))|([1-9]\\d{0," + (maxLen - 1) + "}(([.]\\d{0,2})?)))?"
        if (canNegative) {
            pattern =
                "(\\-)?(([0]|(0[.]\\d{0,2}))|([1-9]\\d{0," + (maxLen - 1) + "}(([.]\\d{0,2})?)))?"
        }
    }

    override fun filter(
        source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int
    ): CharSequence? {
        //获取改变之后的字符串
        var text = ""
        if (end > start) {
            //插入字符串
            if (dstart > 0) {
                text = dest.toString().substring(0, dstart)
            }
            text += source
            if (dstart < dest.toString().length) {
                text += dest.toString().substring(dstart)
            }
        } else {
            //删除字符串
            if (dstart > 0) {
                text = dest.toString().substring(0, dstart)
            }
            if (dest.toString().length > dstart + (dend - dstart)) {
                text += dest.toString().substring(dstart + (dend - dstart))
            }
        }
        return if (Pattern.matches(pattern, text)) {
            null
        } else {
            ""
        }
    }
}